package com.jxstyle.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import com.jxstyle.core.security.BCryptPasswordEncoder;
import com.jxstyle.core.security.LoginFailureHandler;
import com.jxstyle.core.security.LoginSuccessHandler;
import com.jxstyle.core.security.UserDetailService;

/**
 * Created by EalenXie on 2018/1/11.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
	private UserDetailService userDetailService;
	@Autowired
	private BCryptPasswordEncoder bCryptPasswordEncoder;
	@Autowired
	private LoginFailureHandler loginFailureHandler;
	@Autowired
	private LoginSuccessHandler loginSuccessHandler;;
	@Autowired
	private LogoutSuccessHandler logoutSuccessHandler;
	@Value("${jxs.token_expire_seconds}")
	private int token_expire_seconds;
	
	@Override
	protected void configure(HttpSecurity http) throws Exception { // 配置策略
		http.csrf().disable();
		http.authorizeRequests()
		.antMatchers("/static/**","/favicon.ico").permitAll().anyRequest().authenticated()
		.and().rememberMe()                                   // 记住我相关配置
        // 配置Cookie过期时间
        .tokenValiditySeconds(token_expire_seconds).and()
		.formLogin().loginPage("/login")
		.failureForwardUrl("/login?error")
		.loginProcessingUrl("/login").permitAll()
		.successHandler(loginSuccessHandler)
		.failureHandler(loginFailureHandler)
		.and()
		.logout().logoutUrl("/logout").permitAll()
		.invalidateHttpSession(true)
		.deleteCookies("JSESSIONID")
		.logoutSuccessHandler(logoutSuccessHandler)
		.and()
		.sessionManagement()
		.maximumSessions(10)
		.expiredUrl("/login");
		 http.headers().frameOptions().disable();
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailService).passwordEncoder(bCryptPasswordEncoder);
		auth.eraseCredentials(false);
	}
	
}